package com.zjj.io.serial;

import java.io.*;

/**
 * @author zhoujunjie
 * @desc TODO
 * @date
 */
public class Singleton implements Serializable {

    private static final long serialVersionUID = 1453058480339344324L;
    private Singleton(){

    }
    private static class InnerClass{
        private static Singleton singleton = new Singleton();
    }

    public static Singleton getInstance(){
        return InnerClass.singleton;
    }

    private Object readResolve(){
        return InnerClass.singleton;
    }

}
class SingletonTest{

    public static void main(String[] args) {
        try {

            Singleton singleton = Singleton.getInstance();
            System.out.println("singleton = "+singleton);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(singleton);
            oos.flush();
            oos.close();
            System.out.println("序列化完成！");

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            Singleton s = (Singleton)ois.readObject();
            System.out.println("s = "+s);
            ois.close();
            System.out.println(singleton == s);  //false   true
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
